package com.hejl.controller;

import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;

/**
 * @author Hejl
 * @version 1.0
 * @description
 * @className ChatModelController
 * @date 2025/6/9 11:41
 */
@RestController
public class ChatModelController {

    @Autowired
    private ChatModel chatModel;

    //String call(String input)
    @GetMapping("/chatModel01")
    public String chatModel01(@RequestParam(value = "input", defaultValue = "你好") String input) {
        return chatModel.call(input);
    }

    //ChatResponse call(Prompt prompt)
    @GetMapping("/chatModel02")
    public String chatModel02(@RequestParam(value = "input", defaultValue = "你好") String input) {
        ChatResponse call = chatModel.call(new Prompt(input, ChatOptions.builder().model("deepseek-chat").temperature(0.8).build()));
        return call.getResult().getOutput().getText();
    }

    @GetMapping(value = "/chatModel03", produces = "text/html;charset=UTF-8")
    public Flux<String> chatModel03(@RequestParam(value = "input", defaultValue = "你好") String input) {
        return chatModel.stream(input);
    }

    //提示词尝试
    @GetMapping("/prompt")
    public String prompt(@RequestParam(value = "name") String name, @RequestParam(value = "style") String style, @RequestParam(value = "city") String city) {
        //设置用户输入信息
        String userInput = "给我推荐北京的至少3家地道的美食 ";
        UserMessage userMessage = new UserMessage(userInput);
        //设置系统提示信息
        String systemInput = "你是一个美食咨询助手，你的名字是{name}，现在住在{city}城市，你是{style}菜系的狂热者，你应该用你的名字、居住地以及喜欢的菜系和推荐的美食的地址回复用户请求";
        //使用prompt template 设置信息
        SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemInput);
        //替换占位符
        Message message = systemPromptTemplate.createMessage(Map.of("name", name, "style", style, "city", city));
        //调用chatModel
        List<Generation> results = chatModel.call(new Prompt(List.of(message, userMessage))).getResults();
        //遍历输出
        return results.get(0).getOutput().getText();

    }

}